package com.xml.parsing;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import com.db.DictionaryDB;
import com.mongodb.BasicDBObject;

 

public class ParseDictionary {

	private NodeList nodeLst;
	
	ParseDictionary(String dictionaryToParse) {

		try {
			// DOM parsing - tree building
			File file = new File(dictionaryToParse);
			
			DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
			DocumentBuilder db = dbf.newDocumentBuilder();
			Document doc = db.parse(file);
			doc.getDocumentElement().normalize();
			nodeLst = doc.getElementsByTagName("ar");
			
			parseWords();
		}
			
		
		
		catch (Exception e) {
			e.printStackTrace();
		}
		
	}

	public void parseWords() {
		
		DictionaryDB dictionaryDB = new DictionaryDB();
		dictionaryDB.connect();
	 
			 
		for (int s = 0; s < nodeLst.getLength(); s++) {
			
				Node fstNode = nodeLst.item(s);
				Element ar = (Element) fstNode;
				
				NodeList WordChildren = fstNode.getChildNodes();
				
				List<String> translations = new ArrayList<String>();
				
				StringTokenizer strTokenizer = new StringTokenizer(WordChildren.item(1).getNodeValue(),"\n");
		          
				while(strTokenizer.hasMoreTokens()) {
						translations.add(strTokenizer.nextToken());
				}
				
				String[] translationArray = new String[translations.size()];
				translations.toArray(translationArray);
			
				dictionaryDB.insertWord(WordChildren.item(0).getTextContent(), "English", "Magyar", translationArray);
				
		}
		
	}
	
	
	public static void main(String[] args) {
 
		try {
			
			ParseDictionary parsing = new ParseDictionary(args[0].toString());
			
		}
		catch (Exception e) {
			e.printStackTrace();
		}
		
 
	}
	
}
